package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 该线程的任务是与指定的客户端完成HTTP交互
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            //1解析请求
            /*
                测试读取请求行
                请求行是请求的一行内容,以回车符+换行符结尾的一行字符串
             */
            InputStream in = socket.getInputStream();
            StringBuilder builder = new StringBuilder();
            int d;
            char pre='0',cur='0';
            while((d=in.read())!=-1){
                pre = cur;
                cur = (char)d;
                if(pre==13 && cur==10){
                    break;
                }
                builder.append(cur);
            }
            String line = builder.toString().trim();
            System.out.println("请求行："+line);

            //将请求行中的请求方式，抽象路径，协议版本分别解析出来
            //String[] data = line.split(" ");
            String[] data = line.split("\\s");
            String method = data[0];
            String uri = data[1];
            String protocol = data[2];

            System.out.println(method+", "+uri+", "+protocol);


            //2处理请求

            //3发送响应
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
